﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.Web;
using com.dz.common;
namespace com.dz.httpmoudle
{
    public class UrlRewriteModule : IHttpModule
    {
        /// <summary>
        /// 书介绍页
        /// </summary>
        const string book_url = @"(http:)//(\S+)/(\d+).aspx";

        /// <summary>
        /// 书分类列表页
        /// </summary>
        const string category_url = @"(http:)//(\S+)/category/(\S+).aspx";

        /// <summary>
        /// 阅读页
        /// </summary>
        const string reader_url = @"(http:)//(\S+)/chapter/(\d+),(\d+).aspx";

        /// <summary>
        /// 榜单更多页面
        /// </summary>
        const string top_url = @"(http:)//(\S+)/topList/(\d+)/(\d+)/(\d+).aspx";

        /// <summary>
        /// 章节列表页
        /// </summary>
        const string chapter_list_url = @"(http:)//(\S+)/chapterList/(\d+).aspx";

        /// <summary>
        /// 章节内容地址
        /// </summary>
        const string chapter = @"(http:)//(\S+)/ch/(\d+)/(\d+)/(\d+)\.txt";
        /// <summary>
        /// 请求初始
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(BeginRequestHandler);
        }

        private void BeginRequestHandler(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = HttpContext.Current.Request;
       

            string url = request.Url.ToString().ToLower();
            if (url.IndexOf(".aspx") < 0 && url.IndexOf(".txt")<0) return;
            if (url.Contains("/ajax")) return;
            if (url.Contains("/admin")) return;
            if (url.Contains("validatecode")) return;
            if (url.Contains("register")) return;
            try
            {
                //if (url.ToLower().IndexOf("ch") > -1 && url.ToLower().IndexOf("aspx")>-1)
                //{
                //    LogHelper.Info(url);
                //    if (Regex.IsMatch(url, chapter, RegexOptions.IgnoreCase | RegexOptions.Compiled))
                //    {
                //        Match t_mc = Regex.Match(url, chapter, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                //        if (t_mc == null || t_mc.Groups.Count != 6)
                //            return;
                //        string t_category_id = t_mc.Groups[3].Value.ToString();
                //        string t_book_id = t_mc.Groups[4].Value.ToString();
                //        string t_chapter_id = t_mc.Groups[5].Value.ToString();
                //        string t_real_mac = SystemUtil.MD5Mac(string.Format("{0},{1},{2}", t_book_id, t_chapter_id, AppConfig.UrlKey));
                //        string t_cookie_mac = CookieManager.GetChapterCookie();
                //        string realUrl = string.Format("{0}/{1}/{2}/{3}.txt?key={4}", AppConfig.BookChpaterPath, t_category_id, t_book_id, t_chapter_id, t_real_mac);
                //        if (string.IsNullOrEmpty(t_cookie_mac))
                //        {
                //            realUrl = string.Format("{0}/error.txt", AppConfig.BookChpaterPath);

                //        }
                //        if (!string.IsNullOrEmpty(t_cookie_mac) && t_cookie_mac.Equals(t_cookie_mac) == false)
                //        {
                //            realUrl = string.Format("{0}/error.txt", AppConfig.BookChpaterPath);
                //        }

                //        LogHelper.Info(realUrl);
                //        HttpContext.Current.Response.Redirect(realUrl,false);
                //        return;
                //    }
                //}
                if (url.ToLower().IndexOf("wanben") > -1)
                {
                    HttpContext.Current.RewritePath("~/categoryList.aspx?categoryIdList=-1");
                    return;
                }
                if (url.ToLower().IndexOf("chapterlist") > -1)
                {
                    if (Regex.IsMatch(url, chapter_list_url, RegexOptions.IgnoreCase | RegexOptions.Compiled))
                    {
                        string realUrl = Regex.Replace(url, chapter_list_url, "~/ChapterList.aspx?bookId=$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                        HttpContext.Current.RewritePath(realUrl);
                        return;
                    }
                }
                if (Regex.IsMatch(url, reader_url, RegexOptions.IgnoreCase | RegexOptions.Compiled))
                {
                    string realUrl = Regex.Replace(url, reader_url, "~/chapter.aspx?bookId=$3&chapterId=$4", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    HttpContext.Current.RewritePath(realUrl);
                    return;
                }

                if (Regex.IsMatch(url, top_url, RegexOptions.IgnoreCase | RegexOptions.Compiled))
                {
                    string realUrl = Regex.Replace(url, top_url, "~/TopList.aspx?type=$3&totalCount=$4&pageIndex=$5", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    HttpContext.Current.RewritePath(realUrl);
                    return;
                }

                if (Regex.IsMatch(url, category_url, RegexOptions.IgnoreCase | RegexOptions.Compiled))
                {
                    string realUrl = Regex.Replace(url, category_url, "~/categoryList.aspx?categoryIdList=$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    HttpContext.Current.RewritePath(realUrl);
                    return;
                }

                if (Regex.IsMatch(url, book_url, RegexOptions.IgnoreCase | RegexOptions.Compiled))
                {
                    string realUrl = Regex.Replace(url, book_url, "~/bookIntro.aspx?bookId=$3", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    HttpContext.Current.RewritePath(realUrl);
                    return;

                }

                
            }
            catch (Exception ex)
            {
               LogHelper.Error("重写url出现异常" + ex.ToString());
                return;
            }

        }
        public void Dispose()
        {
            // throw new Exception( "The method or operation is not implemented." );
        }

        /// <summary>
        /// 从url中解析文件名
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string GetFileName(string Url)
        {
            if (Url == null)
                throw new ArgumentNullException("fileName", "文件路径名称为空");

            if (Url.Length == 0 || Url.IndexOf(".") == -1) return string.Empty;


            Url = Url.ToLower().Replace(@"/", @"\");

            if (Url.IndexOf("\\") != -1)
            {
                string[] filePieces = Url.Split('\\');
                string path = filePieces[filePieces.Length - 1];

                int len = path.IndexOf(".aspx");

                if (len > 0)
                {

                    return path.Substring(0, len) + ".aspx";
                }
                else
                {
                    return path;
                }

            }
            else
            {
                return Url;
            }
        }
    }
}
